package App.Controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Created by xw on 2018/11/14.
 */

@RestController
public class RedisController {

    @Autowired
    private StringRedisTemplate template;

    @RequestMapping("redis")
    public String testResis() {
        String result = "";
        try {
            ValueOperations<String, String> ops = this.template.opsForValue();
            String key = "spring.boot.redis.test";
            template.expire(key, 40, TimeUnit.SECONDS);
            if (!this.template.hasKey(key)) {
                ops.set(key, "foo");

            } else {
                for (int i = 1; i < 10; i++) {
                    Date d = new Date();
                    // ops.set(Integer.toString(i), d.toString());
                }
            }
            result = "Found key " + key + ", value=" + ops.get(key);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

    @RequestMapping("remove")
    public String remove() {

        //redisTemplate.expire(key, time, TimeUnit.SECONDS);

        String _key = "spring.boot.redis.test";


        ValueOperations<String, String> operator = this.template.opsForValue();

        for (int i = 1; i < 10; i++) {
            _key = Integer.toString(i);
            if (template.hasKey(_key)) {
                template.delete(_key);
            }
        }
        return "remove";
    }

    @RequestMapping("expire")
    public String expire() {
        String _key = "spring.boot.redis.test";
        template.expire(_key, 40, TimeUnit.SECONDS);
        return "expire";
    }


    @RequestMapping("select")
    public String select() {

        String result="";
        String _key = "spring.boot.redis.test";
        ValueOperations<String, String> operator = this.template.opsForValue();
        if (template.hasKey(_key)) {
             result = operator.get(_key);
        }
        else{
            result="can not find the key";
        }
        return result;

    }
}
